package sunwul.mall.commoncore.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import sunwul.mall.commoncore.properties.SwaggerProperties;

import java.util.HashSet;

/**
 * @author sunwul
 * @date 2024/12/27 15:25
 * @description swagger自动装配
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Autowired
    private Environment environment;

    @Bean
    public Docket docket() {
        boolean flag = true;
        // 获取使用环境, 根据不同环境控制是否生成文档
        String[] activeProfiles = environment.getActiveProfiles();
        for (String profile : activeProfiles) {
            if (profile.equals("pro")) {
                flag = false;
                break;
            }
        }

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(getApiInfo())
                .enable(flag) // 根据环境开启
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) // 扫描需要生成文档的包
                .build();
    }

    private ApiInfo getApiInfo() {
        Contact contact = new Contact(
                swaggerProperties.getAuthor(),
                swaggerProperties.getUrl(),
                swaggerProperties.getEmail()
        );

        return new ApiInfo(
                swaggerProperties.getTitle(),
                swaggerProperties.getDescription(),
                swaggerProperties.getVersion(),
                swaggerProperties.getTermsOfServiceUrl(),
                contact,
                swaggerProperties.getLicense(),
                swaggerProperties.getLicenseUrl(),
                new HashSet<>()
        );
    }
}
